<?php


namespace App\Dao;


use App\Kernel\Traits\DaoTrait;
use App\Model\StoreGroup;
use Hyperf\Database\Model\Builder;

/**
 * @author 陈奕文
 * @package App\Dao
 */
class StoreGroupDao extends Dao
{
    use DaoTrait;

    /**
     * Get model.
     *
     * @return string
     */
    public function model(): string
    {
        return StoreGroup::class;
    }

    /**
     * 获得单个用户组通过ID
     * @param int $id
     * @return mixed
     */
    public function getGroupById(int $id)
    {
        return StoreGroup::query()->where('id', $id)->first();
    }

    /**
     * 获得单个用户组通过组名称
     * @param string $name
     * @return mixed
     */
    public function getGroupByName(string $name)
    {
        return StoreGroup::query()->where('group_name', $name)->first();
    }


    /**
     * 获得多个用户组通过多个ID
     * @param array $ids
     * @param array $select
     * @return mixed
     */
    public function getGroupsByIds(array $ids, array $select = ['*'])
    {
        return StoreGroup::query()->whereIn('id', $ids)->select($select)->get();
    }

    /**
     * 通过map获取后台用户组
     * @param array $map
     * @param string|null $sort
     * @param array|null $select
     * @param int|null $paginate
     * @return mixed
     */
    public function getStoreGroupByMap(array $map = [], string $sort = null,array $select = null, int $paginate = null)
    {
        $model = self::makeModel();

        if (isset($map['between_field'])) {
            foreach ($map['between_field'] as $k => $value) {
                $model = $model->whereBetween($k, $value);
            }
            unset($map['between_field']);
        }

        // 或
        if (isset($map['or_field'])) {
            $model = $model->where(function (Builder $query) use($map) {
                foreach ($map['or_field'] as $field => $item) {
                    // 普通查询
                    if (!is_array($item)) {
                        $query->orWhere($field, $item);
                        continue;
                    }
                    // 其它方式
                    switch (strtolower($item[0])) {
                        case 'in':
                            $query->orWhereIn($field, $item[1]);
                            break;

                        default:
                            $query->orWhere($field, $item[0], $item[1]);
                    }
                }
            });

            unset($map['or_field']);
        }

        if (!empty($map)) {
            $model = $model->where(function ($query) use ($map) {
                return queryWhere($query, $map);
            });
        }
        if (null !== $sort) {
            $model = $model->orderByRaw($sort);
        }

        if (null !== $select) {
            $model = $model->select($select);
        }

        return $paginate > 0 ? $model->paginate($paginate) : $model->get();

    }


}